package git.soulbgm.security.handler;

import git.soulbgm.common.constant.HttpStatus;
import git.soulbgm.common.pojo.ResultData;
import git.soulbgm.common.pojo.ReturnCode;
import git.soulbgm.pojo.entity.User;
import git.soulbgm.security.pojo.LoginUser;
import git.soulbgm.utils.JsonUtil;
import git.soulbgm.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义注销成功处理类
 *
 * @author SoulBGM
 * @date 2020-07-30
 */
@Slf4j
@Service("logoutSuccessHandler")
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (authentication != null) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            log.info("{},退出成功", loginUser.getNickname());
            ResultData resultData = ResultData.getResultData(ReturnCode.SUCCESS);
            ResponseUtil.renderJson(response, JsonUtil.toJson(resultData));
        } else {
            ResponseUtil.renderError(response, HttpStatus.UNAUTHORIZED);
        }
    }
}
